<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="医生姓名" prop="doctorName">
        <el-input
          v-model="queryParams.doctorName"
          placeholder="请输入医生姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="科室名称" prop="deptName">
        <el-input
          v-model="queryParams.deptName"
          placeholder="请输入科室名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="排班日期" prop="date">
        <el-date-picker
          clearable
          v-model="queryParams.date"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择排班日期"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['schedules:schedules:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['schedules:schedules:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['schedules:schedules:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['schedules:schedules:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="schedulesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column label="医生姓名" align="center" prop="doctorName" />
      <el-table-column label="所属科室" align="center" prop="deptName" />
      <el-table-column label="排班日期" align="center" prop="date" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.date, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="上午值班时间" align="center" width="180">
        <template slot-scope="scope">
          <div class="time-slot">
            <div class="time-info">
              <span>{{ scope.row.morningStart }} - {{ scope.row.morningEnd }}</span>
            </div>
            <div class="stock-info" :class="{ 'low-stock': scope.row.morningRemaining < 5 }" v-if="scope.row.morningStart && scope.row.morningEnd">
              号源剩余: {{ scope.row.morningRemaining }}
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="下午值班时间" align="center" width="180">
        <template slot-scope="scope">
          <div class="time-slot">
            <div class="time-info">
              <span>{{ scope.row.afternoonStart }} - {{ scope.row.afternoonEnd }}</span>
            </div>
            <div class="stock-info" :class="{ 'low-stock': scope.row.afternoonRemaining < 5 }" v-if="scope.row.afternoonStart && scope.row.afternoonEnd">
              号源剩余: {{ scope.row.afternoonRemaining }}
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="夜间值班时间" align="center" width="180">
        <template slot-scope="scope">
          <div class="time-slot">
            <div class="time-info">
              <span>{{ scope.row.nightStart }} - {{ scope.row.nightEnd }}</span>
            </div>
            <div class="stock-info" :class="{ 'low-stock': scope.row.nightRemaining < 5 }" v-if="scope.row.nightStart && scope.row.nightEnd">
              号源剩余: {{ scope.row.nightRemaining }}
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['schedules:schedules:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['schedules:schedules:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改排班信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label=" 医生姓名 " prop="doctorName">
              <el-select v-model="form.doctorId" placeholder="请选择医生">
                <el-option
                  v-for="dict in doctorsList"
                  :key="dict.doctorId"
                  :label="dict.doctorName"
                  :value="dict.doctorId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label=" 排班日期 " prop="date">
              <el-date-picker
                clearable
                v-model="form.date"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择排班日期"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上午开始时间" prop="morningStart">
              <el-time-picker
                clearable
                v-model="form.morningStart"
                format="HH:mm"
                value-format="HH:mm"
                placeholder="请选择上午开始时间"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上午结束时间" prop="morningEnd">
              <el-time-picker
                clearable
                v-model="form.morningEnd"
                format="HH:mm"
                value-format="HH:mm"
                placeholder="请选择上午结束时间"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下午开始时间" prop="afternoonStart">
              <el-time-picker
                clearable
                v-model="form.afternoonStart"
                format="HH:mm"
                value-format="HH:mm"
                placeholder="请选择下午开始时间"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下午结束时间" prop="afternoonEnd">
              <el-time-picker
                clearable
                v-model="form.afternoonEnd"
                format="HH:mm"
                value-format="HH:mm"
                placeholder="请选择下午结束时间"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="夜间开始时间" prop="nightStart">
              <el-time-picker
                clearable
                v-model="form.nightStart"
                format="HH:mm"
                value-format="HH:mm"
                placeholder="请选择夜间开始时间"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="夜间结束时间" prop="nightEnd">
              <el-time-picker
                clearable
                v-model="form.nightEnd"
                format="HH:mm"
                value-format="HH:mm"
                placeholder="请选择夜间结束时间"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上午号源数量" prop="morningQuota">
              <el-input v-model="form.morningQuota" placeholder="请输入上午号源数量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="剩余号源数量" prop="morningRemaining">
              <el-input v-model="form.morningRemaining" placeholder="请输入上午剩余号源数量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下午号源数量" prop="afternoonQuota">
              <el-input v-model="form.afternoonQuota" placeholder="请输入下午号源数量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="剩余号源数量" prop="afternoonRemaining">
              <el-input v-model="form.afternoonRemaining" placeholder="请输入下午剩余号源数量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="夜间号源数量" prop="nightQuota">
              <el-input v-model="form.nightQuota" placeholder="请输入夜间号源数量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="剩余号源数量" prop="nightRemaining">
              <el-input v-model="form.nightRemaining" placeholder="请输入夜间剩余号源数量" />
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSchedules, getSchedules, delSchedules, addSchedules, updateSchedules } from "@/api/schedules/schedules";
import {getAllDoctors} from "../../../api/doctors/doctors";

export default {
  name: "Schedules",
  data() {
    return {
      doctorsList: [],
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      schedulesList: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        doctorId: null,
        doctorName: null,
        deptName: null,
        date: null,
      },
      form: {},
      rules: {
        date: [
          {required: true, message: "排班日期不能为空", trigger: "blur"},
        ],
        morningStart: [
          {required: false, message: "上午开始时间不能为空", trigger: "blur"},
        ],
        morningEnd: [
          {
            required: false,
            message: "上午结束时间不能为空",
            trigger: "blur"
          },
          {
            validator: (rule, value, callback) => {
              if (this.form.morningStart && value && this.form.morningStart >= value) {
                callback(new Error("上午结束时间需晚于开始时间"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        afternoonStart: [
          {required: false, message: "下午开始时间不能为空", trigger: "blur"},
        ],
        afternoonEnd: [
          {
            required: false,
            message: "下午结束时间不能为空",
            trigger: "blur"
          },
          {
            validator: (rule, value, callback) => {
              if (this.form.afternoonStart && value && this.form.afternoonStart >= value) {
                callback(new Error("下午结束时间需晚于开始时间"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        nightStart: [
          {required: false, message: "夜间开始时间不能为空", trigger: "blur"},
        ],
        nightEnd: [
          {
            required: false,
            message: "夜间结束时间不能为空",
            trigger: "blur"
          },
          {
            validator: (rule, value, callback) => {
              if (this.form.nightStart && value && this.form.nightStart >= value) {
                callback(new Error("夜间结束时间需晚于开始时间"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        morningQuota: [
          {
            validator: (rule, value, callback) => {
              const hasMorningTime = this.form.morningStart && this.form.morningEnd;
              if (hasMorningTime) {
                if (isNaN(value)) {
                  callback(new Error("请输入有效的数字"));
                } else {
                  callback();
                }
              } else {
                if (value !== null && value !== undefined && value !== '') {
                  callback(new Error("无上午值班时间，不能填写上午号源数量"));
                } else {
                  callback();
                }
              }
            }
          },
        ],
        morningRemaining: [
          {
            validator: (rule, value, callback) => {
              const hasMorningTime = this.form.morningStart && this.form.morningEnd;
              if (hasMorningTime) {
                if (isNaN(value)) {
                  callback(new Error("请输入有效的数字"));
                } else {
                  if (value && this.form.morningQuota && value > this.form.morningQuota) {
                    callback(new Error("上午剩余号源不能大于总号源数量"));
                  } else {
                    callback();
                  }
                }
              } else {
                if (value !== null && value !== undefined && value !== '') {
                  callback(new Error("无上午值班时间，不能填写上午剩余号源数量"));
                } else {
                  callback();
                }
              }
            }
          },
        ],
        afternoonQuota: [
          {
            validator: (rule, value, callback) => {
              const hasAfternoonTime = this.form.afternoonStart && this.form.afternoonEnd;
              if (hasAfternoonTime) {
                if (isNaN(value)) {
                  callback(new Error("请输入有效的数字"));
                } else {
                  callback();
                }
              } else {
                if (value !== null && value !== undefined && value !== '') {
                  callback(new Error("无下午值班时间，不能填写下午号源数量"));
                } else {
                  callback();
                }
              }
            }
          },
        ],
        afternoonRemaining: [
          {
            validator: (rule, value, callback) => {
              const hasAfternoonTime = this.form.afternoonStart && this.form.afternoonEnd;
              if (hasAfternoonTime) {
                if (isNaN(value)) {
                  callback(new Error("请输入有效的数字"));
                } else {
                  if (value && this.form.afternoonQuota && value > this.form.afternoonQuota) {
                    callback(new Error("下午剩余号源不能大于总号源数量"));
                  } else {
                    callback();
                  }
                }
              } else {
                if (value !== null && value !== undefined && value !== '') {
                  callback(new Error("无下午值班时间，不能填写下午剩余号源数量"));
                } else {
                  callback();
                }
              }
            }
          },
        ],
        nightQuota: [
          {
            validator: (rule, value, callback) => {
              const hasNightTime = this.form.nightStart && this.form.nightEnd;
              if (hasNightTime) {
                if (isNaN(value)) {
                  callback(new Error("请输入有效的数字"));
                } else {
                  callback();
                }
              } else {
                if (value !== null && value !== undefined && value !== '') {
                  callback(new Error("无夜间值班时间，不能填写夜间号源数量"));
                } else {
                  callback();
                }
              }
            }
          },
        ],
        nightRemaining: [
          {
            validator: (rule, value, callback) => {
              const hasNightTime = this.form.nightStart && this.form.nightEnd;
              if (hasNightTime) {
                if (isNaN(value)) {
                  callback(new Error("请输入有效的数字"));
                } else {
                  if (value && this.form.nightQuota && value > this.form.nightQuota) {
                    callback(new Error("夜间剩余号源不能大于总号源数量"));
                  } else {
                    callback();
                  }
                }
              } else {
                if (value !== null && value !== undefined && value !== '') {
                  callback(new Error("无夜间值班时间，不能填写夜间剩余号源数量"));
                } else {
                  callback();
                }
              }
            }
          },
        ],
      },
    }
  },
  created() {
    this.getList();
    this.getAllDoctors(); // 初始化时获取医生列表
  },
  methods: {
    // 获取医生列表
    getAllDoctors() {
      getAllDoctors().then(response => {
        this.doctorsList = response.data
      })
    },
    getList() {
      this.loading = true;
      listSchedules(this.queryParams).then((response) => {
        this.schedulesList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        scheduleId: null,
        doctorId: null,
        date: null,
        morningStart: null,
        morningEnd: null,
        afternoonStart: null,
        afternoonEnd: null,
        nightStart: null,
        nightEnd: null,
        morningQuota: null,
        afternoonQuota: null,
        nightQuota: null,
        morningRemaining: null,
        afternoonRemaining: null,
        nightRemaining: null,
        createTime: null,
        updateTime: null,
        deleted: null,
      };
      this.resetForm("form");
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.scheduleId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加排班信息";
    },
    handleUpdate(row) {
      this.reset();
      const scheduleId = row.scheduleId || this.ids;
      getSchedules(scheduleId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改排班信息";
      });
    },
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // 自定义验证：如果开始时间存在但结束时间不存在，或者反之
          if ((this.form.morningStart && !this.form.morningEnd) || (!this.form.morningStart && this.form.morningEnd)) {
            this.$message.error("上午开始和结束时间需同时填写或同时为空");
            return;
          }

          if ((this.form.afternoonStart && !this.form.afternoonEnd) || (!this.form.afternoonStart && this.form.afternoonEnd)) {
            this.$message.error("下午开始和结束时间需同时填写或同时为空");
            return;
          }

          if ((this.form.nightStart && !this.form.nightEnd) || (!this.form.nightStart && this.form.nightEnd)) {
            this.$message.error("夜间开始和结束时间需同时填写或同时为空");
            return;
          }

          // 自定义验证：如果填写了号源数量，剩余号源不能大于总号源
          if (this.form.morningRemaining > this.form.morningQuota) {
            this.$message.error("上午剩余号源不能大于总号源数量");
            return;
          }

          if (this.form.afternoonRemaining > this.form.afternoonQuota) {
            this.$message.error("下午剩余号源不能大于总号源数量");
            return;
          }

          if (this.form.nightRemaining > this.form.nightQuota) {
            this.$message.error("夜间剩余号源不能大于总号源数量");
            return;
          }

          // 初始化剩余号源（如果新增时未填写）
          if (!this.form.scheduleId) {
            if (this.form.morningQuota && this.form.morningRemaining === null) {
              this.form.morningRemaining = this.form.morningQuota;
            }
            if (this.form.afternoonQuota && this.form.afternoonRemaining === null) {
              this.form.afternoonRemaining = this.form.afternoonQuota;
            }
            if (this.form.nightQuota && this.form.nightRemaining === null) {
              this.form.nightRemaining = this.form.nightQuota;
            }
          }

          // 转换日期格式
          if (this.form.date && typeof this.form.date === 'string') {
            // 不需要转换为 Date 对象，MyBatis 可以直接处理字符串格式的日期
            // 但需要确保格式为 yyyy-MM-dd
          }

          // 提交表单
          if (this.form.scheduleId) {
            updateSchedules(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSchedules(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleDelete(row) {
      const scheduleIds = row.scheduleId || this.ids;
      // 简单判断：若有预约（剩余号源 < 号源数量），则禁止删除
      if (row.morningRemaining < row.morningQuota || row.afternoonRemaining < row.afternoonQuota || row.nightRemaining < row.nightQuota) {
        this.$modal.warning("该排班已有预约，暂无法删除");
        return;
      }
      this.$modal.confirm("是否确认删除排班信息编号为'" + scheduleIds + "'的数据项？").then(() => {
        return delSchedules(scheduleIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleExport() {
      this.download("schedules/schedules/export", {
        ...this.queryParams,
      }, `schedules_${new Date().getTime()}.xlsx`);
    },
  },
};
</script>

<style scoped>
/* 基础布局 */
.time-slot {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 8px 0;
}

/* 时间与号源垂直排列 */
.time-info, .stock-info {
  width: 100%;
  text-align: center;
  padding: 2px 0;
}

.time-info {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
}

.stock-info {
  font-size: 12px;
  color: #606266;
  margin-top: 4px;
}

/* 低库存红色提示 */
.low-stock {
  color: #f56c6c;
  font-weight: 500;
}

</style>
